<template>
  <section class="space-y-4 pb-16">
    <!-- 筛选条件区域 - 与入账记录页面保持一致 -->
    <div class="bg-white rounded-2xl p-4 shadow-sm border border-gray-100">
      <!-- 时间筛选 -->
      <div class="space-y-3">
        <!-- 范围时间选择 -->
        <div class="grid grid-cols-2 gap-2">
          <input type="date" v-model="startDate" 
                 @change="handleDateChangeAndReload"
                 :min="minDate" :max="maxDate"
                 placeholder="开始日期"
                 class="px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
          <input type="date" v-model="endDate"
                 @change="handleDateChangeAndReload"
                 :min="minDate" :max="maxDate"
                 placeholder="结束日期"
                 class="px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
        </div>

        <!-- 快捷时间选项 -->
        <div class="flex gap-1">
          <button v-for="option in quickOptions" :key="option.value" 
                  @click="selectQuickOptionAndReload(option.value)"
                  :class="[
                    'px-3 py-1.5 rounded text-sm font-medium transition-all whitespace-nowrap flex-1',
                    quickTime === option.value 
                      ? 'bg-brand-500 text-white border border-brand-500' 
                      : 'bg-gray-50 text-gray-600 hover:bg-gray-100 border border-gray-200'
                  ]">
            {{ option.label }}
          </button>
        </div>
      </div>

      <!-- 场站筛选 -->
      <div class="flex items-center justify-between mt-4 pt-4 border-t border-gray-100">
        <div class="text-sm font-medium text-gray-700">场站筛选</div>
        <div class="relative">
          <button @click="toggleSitePicker($event)"
                  class="inline-flex items-center gap-1 px-3 py-1.5 border border-gray-200 bg-white rounded-md text-sm text-gray-700 hover:bg-gray-50 shadow-sm">
            <span class="truncate max-w-[180px]">{{ selectedSite ? selectedSite.stationName : '全部场站' }}</span>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-4 h-4 text-gray-500"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 9l6 6 6-6"/></svg>
          </button>
          <!-- 场站下拉选择 -->
          <div v-if="showSitePicker" v-click-outside="closeSitePicker" class="absolute right-0 top-full mt-2 z-20 rounded-lg bg-white text-gray-900 shadow-lg ring-1 ring-black/5 max-h-[12rem] overflow-y-auto">
            <button class="block w-full text-left px-3 py-2 hover:bg-gray-50 text-sm whitespace-nowrap" @click="selectSite(null)">全部场站</button>
            <div>
              <button v-for="s in sites" :key="s.stationId" class="block w-full text-left px-3 py-2 hover:bg-gray-50 text-sm whitespace-nowrap" @click="selectSite(s.stationId)">
                {{ s.stationName }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="bg-gradient-to-r from-brand-500 to-brand-600 rounded-2xl p-4 shadow-sm text-white">
      <div class="grid grid-cols-3 gap-4">
        <!-- 总服务费 -->
        <div class="text-center">
          <div class="text-xs opacity-90 mb-1">总服务费</div>
          <div class="text-lg font-bold">¥{{ formatNumber(totalServiceFee) }}</div>
        </div>
        <!-- 总实际收入 -->
        <div class="text-center">
          <div class="text-xs opacity-90 mb-1">总实际收入</div>
          <div class="text-lg font-bold">¥{{ formatNumber(totalActualIncome) }}</div>
        </div>
        <!-- 订单数量 -->
        <div class="text-center">
          <div class="text-xs opacity-90 mb-1">总订单数量</div>
          <div class="text-lg font-bold">{{ totalCount }}</div>
        </div>
      </div>
    </div>

    <!-- 记录数量统计 -->
    <div class="flex justify-between items-center">
      <div class="text-sm text-gray-500">筛选结果</div>
      <div class="text-sm text-gray-500">共 {{ totalCount }} 条记录</div>
    </div>

    <!-- 订单列表 -->
    <div class="space-y-3">
      <div v-if="loading" class="flex justify-center items-center py-8">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-500"></div>
      </div>
      
      <div v-else-if="orders.length === 0" class="bg-white rounded-lg p-8 shadow-sm border border-gray-100 text-center">
        <div class="flex flex-col items-center justify-center space-y-3">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-12 h-12 text-gray-300">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
          </svg>
          <div class="text-gray-500 text-sm">暂无符合条件的订单</div>
          <div class="text-gray-400 text-xs">请尝试调整筛选条件</div>
        </div>
      </div>
      
      <div v-else v-for="order in orders" :key="order.profitOrderId" 
           @click="selectOrder(order)"
           class="bg-white rounded-lg p-4 shadow-sm border border-gray-100 hover:shadow-md transition-shadow cursor-pointer">
        <!-- 设备信息 -->
        <div class="mb-4">
          <div class="text-base font-bold text-gray-900">
            {{ order.stationName }}·{{ order.pileName }}·{{ order.gunName }}
          </div>
        </div>
        
        <!-- 费用信息 -->
        <div class="grid grid-cols-4 gap-1.5">
          <div class="bg-gray-50 rounded-lg p-2.5 text-center min-w-0">
            <div class="text-xs text-gray-500 mb-1 whitespace-nowrap overflow-hidden">总服务费</div>
            <div class="text-sm font-medium text-gray-900">¥{{ formatNumber(order.serviceFeeTotal) }}</div>
          </div>
          <div class="bg-gray-50 rounded-lg p-2.5 text-center min-w-0">
            <div class="text-xs text-gray-500 mb-1 whitespace-nowrap overflow-hidden">分成比例</div>
            <div class="text-sm font-medium text-gray-900">{{ order.shareRatio }}%</div>
          </div>
          <div class="bg-gray-50 rounded-lg p-2.5 text-center min-w-0">
            <div class="text-xs text-gray-500 mb-1 whitespace-nowrap overflow-hidden">实际收入</div>
            <div class="text-sm font-medium text-gray-900">¥{{ formatNumber(order.actualIncome) }}</div>
          </div>
          <div class="bg-gray-50 rounded-lg p-2.5 text-center min-w-0">
            <div class="text-xs text-gray-500 mb-1 whitespace-nowrap overflow-hidden">其他费用</div>
            <div class="text-sm font-medium text-gray-900">¥{{ formatNumber(order.otherFee) }}</div>
          </div>
        </div>
        
        <!-- 时间和运营商 -->
        <div class="mt-3 flex items-center justify-between text-xs text-gray-500">
          <div>运营商：{{ order.orgName }}</div>
          <div>入账时间：{{ formatTime(order.inComeTime) }}</div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div class="text-center py-4">
      <button v-if="hasMore" @click="loadMore" class="text-sm text-gray-600 hover:text-gray-900 px-4 py-2 border border-gray-200 rounded-lg hover:border-gray-300 transition-colors">
        加载更多记录
      </button>
      <div v-else class="text-sm text-gray-500">没有更多记录了</div>
    </div>

    <!-- 订单详情弹窗 -->
    <div v-if="selectedOrder" class="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4">
      <div class="bg-white rounded-2xl w-full max-w-md max-h-[80vh] overflow-y-auto">
        <!-- 弹窗头部 -->
        <div class="p-4 border-b border-gray-100">
          <div class="flex items-center justify-between">
            <h3 class="text-lg font-semibold text-gray-900">订单详情</h3>
            <button @click="selectedOrder = null" class="p-1 rounded-full hover:bg-gray-100">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-5 h-5">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
              </svg>
            </button>
          </div>
        </div>
        
        <!-- 详情内容 -->
        <div class="p-4 space-y-4">
        <!-- 订单编号 -->
        <div class="flex">
          <div class="text-base text-gray-500 font-medium w-24 flex-shrink-0">订单编号：</div>
          <div class="text-base font-medium text-gray-900 -ml-1">{{ selectedOrder.profitOrderId }}</div>
        </div>
        
        <!-- 设备信息 -->
        <div class="flex">
          <div class="text-base text-gray-500 font-medium w-24 flex-shrink-0">设备信息：</div>
          <div class="text-base font-medium text-gray-900 -ml-1">
            {{ selectedOrder.stationName }}·{{ selectedOrder.pileName }}·{{ selectedOrder.gunName }}
          </div>
        </div>
        
        <!-- 运营商 -->
        <div class="flex">
          <div class="text-base text-gray-500 font-medium w-24 flex-shrink-0">运营商：</div>
          <div class="text-base font-medium text-gray-900 -ml-1">{{ selectedOrder.orgName }}</div>
        </div>
        
        <!-- 时间信息 -->
        <div class="flex">
          <div class="text-base text-gray-500 font-medium w-24 flex-shrink-0">入账时间：</div>
          <div class="text-base font-medium text-gray-900 -ml-1">{{ formatTime(selectedOrder.inComeTime) }}</div>
        </div>
          
          <!-- 费用明细标题 -->
          <div class="pt-2">
            <div class="text-base text-gray-500 font-medium">费用明细</div>
          </div>
          
          <!-- 费用明细卡片 -->
          <div class="grid grid-cols-2 gap-2">
            <div class="bg-gray-50 rounded-lg p-3 text-center">
              <div class="text-sm text-gray-500 mb-1 whitespace-nowrap overflow-hidden">总服务费</div>
              <div class="text-base font-medium text-gray-900">¥{{ formatNumber(selectedOrder.serviceFeeTotal) }}</div>
            </div>
            <div class="bg-gray-50 rounded-lg p-3 text-center">
              <div class="text-sm text-gray-500 mb-1 whitespace-nowrap overflow-hidden">分成比例</div>
              <div class="text-base font-medium text-gray-900">{{ selectedOrder.shareRatio }}%</div>
            </div>
            <div class="bg-gray-50 rounded-lg p-3 text-center">
              <div class="text-sm text-gray-500 mb-1 whitespace-nowrap overflow-hidden">实际收入</div>
              <div class="text-base font-medium text-gray-900">¥{{ formatNumber(selectedOrder.actualIncome) }}</div>
            </div>
            <div class="bg-gray-50 rounded-lg p-3 text-center">
              <div class="text-sm text-gray-500 mb-1 whitespace-nowrap overflow-hidden">其他费用</div>
              <div class="text-base font-medium text-gray-900">¥{{ formatNumber(selectedOrder.otherFee) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { getOrderList } from '../api/order'
import { getSimpleStationList } from '../api/station'

// 订单数据相关状态
const orders = ref([])
const selectedOrder = ref(null)
const hasMore = ref(true)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const lastId = ref('')

// 统计数据
const totalServiceFee = ref(0)
const totalActualIncome = ref(0)

// 场站数据 - 不再通过props传入，而是直接调用API
const sites = ref([])
const showSitePicker = ref(false)
const selectedSiteId = ref(null)
const selectedSite = computed(() => sites.value?.find(s => s.id === selectedSiteId.value) || null)

// 选中场站显示名称
const selectedSiteName = computed(() => {
  if (!selectedSiteId.value) {
    return '全部场站'
  }
  const site = selectedSite.value
  return site ? site.name : '选择场站'
})

// 点击外部关闭下拉菜单的自定义指令
const vClickOutside = {
  mounted(el, binding) {
    el._clickOutsideHandler = (event) => {
      if (!(el === event.target || el.contains(event.target))) {
        binding.value(event)
      }
    }
    document.addEventListener('click', el._clickOutsideHandler)
  },
  unmounted(el) {
    document.removeEventListener('click', el._clickOutsideHandler)
  }
}

// 时间筛选
const startDate = ref('')
const endDate = ref('')
const quickTime = ref('today')
const quickOptions = [
  { label: '今天', value: 'today' },
  { label: '昨天', value: 'yesterday' },
  { label: '近7天', value: '7days' },
  { label: '全部', value: 'all' }
]

// 日期范围限制
const minDate = computed(() => {
  const date = new Date()
  date.setFullYear(date.getFullYear() - 1)
  return date.toISOString().split('T')[0]
})

const maxDate = computed(() => {
  return new Date().toISOString().split('T')[0]
})

// 方法
const handleDateChange = () => {
  quickTime.value = ''
}

const handleDateChangeAndReload = () => {
  quickTime.value = ''
  handleFilterChange()
}

const selectQuickOption = (value) => {
  quickTime.value = value
  const today = new Date()
  
  switch (value) {
    case 'today':
      startDate.value = today.toISOString().split('T')[0]
      endDate.value = today.toISOString().split('T')[0]
      break
    case 'yesterday':
      const yesterday = new Date(today)
      yesterday.setDate(yesterday.getDate() - 1)
      startDate.value = yesterday.toISOString().split('T')[0]
      endDate.value = yesterday.toISOString().split('T')[0]
      break
    case '7days':
      const weekAgo = new Date(today)
      weekAgo.setDate(weekAgo.getDate() - 6)
      startDate.value = weekAgo.toISOString().split('T')[0]
      endDate.value = today.toISOString().split('T')[0]
      break
    case 'all':
      // 全部选项设置为2025年1月1日到今天
      startDate.value = '2025-01-01'
      endDate.value = today.toISOString().split('T')[0]
      break
  }
}

const selectQuickOptionAndReload = (value) => {
  selectQuickOption(value)
  handleFilterChange()
}

// 切换场站选择器显示状态
const toggleSitePicker = (event) => {
  if (event) event.stopPropagation() // 阻止事件冒泡
  showSitePicker.value = !showSitePicker.value
}

// 关闭场站选择器
const closeSitePicker = () => {
  showSitePicker.value = false
}

const selectSite = (id) => {
  selectedSiteId.value = id
  showSitePicker.value = false
  // 选择场站后重新加载数据
  handleFilterChange()
}

const selectOrder = (order) => {
  selectedOrder.value = order
}

const formatTime = (time) => {
  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 格式化数字，支持字符串和数字类型
const formatNumber = (value) => {
  if (value === null || value === undefined || value === '') return '0.00'
  const num = typeof value === 'string' ? parseFloat(value) : Number(value)
  return isNaN(num) ? '0.00' : num.toFixed(2)
}

// 调用API获取订单列表
const fetchOrderList = async () => {
  try {
    loading.value = true
    
    // 构建请求参数
    const params = {
      lastId: currentPage.value === 1 ? '' : lastId.value,
      stationId: selectedSiteId.value,
      startTime: startDate.value || '',
      endTime: endDate.value || ''
    }
    
    // 调用API - 请求拦截器会自动处理登录状态
    const response = await getOrderList(params)
    
    if (response.success && response.data) {
      const orderList = response.data.list || []
      
      if (currentPage.value === 1) {
        // 第一页，直接替换数据
        orders.value = orderList
        // 设置最后一页的 lastId
        if (orderList.length > 0) {
          lastId.value = orderList[orderList.length - 1].profitOrderId
        }
        
        // 更新统计数据（直接使用接口返回的数据，不额外调用）
        totalServiceFee.value = response.data.totalServiceFee || 0
        totalActualIncome.value = response.data.totalActualIncome || 0
      } else {
        // 分页加载，追加数据
        orders.value = [...orders.value, ...orderList]
        // 更新最后一页的 lastId
        if (orderList.length > 0) {
          lastId.value = orderList[orderList.length - 1].profitOrderId
        }
      }
      
      // 更新总记录数
      totalCount.value = response.data.total || 0
      
      // 判断是否还有更多数据
      hasMore.value = orderList.length >= pageSize.value
    } else {
      console.error('获取订单列表失败:', response.message || '未知错误')
    }
  } catch (error) {
    console.error('获取订单列表异常:', error)
  } finally {
    loading.value = false
  }
}

// 筛选条件变化时重新获取数据
const handleFilterChange = () => {
  currentPage.value = 1
  lastId.value = '' // 重置 lastId
  // 重置统计数据
  totalServiceFee.value = 0
  totalActualIncome.value = 0
  fetchOrderList()
}

// 加载更多记录
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    currentPage.value += 1
    fetchOrderList()
  }
}

// 获取场站列表
const fetchStationList = async () => {
  try {
    console.log('开始获取场站列表...')
    const response = await getSimpleStationList()
    console.log('场站列表API响应:', JSON.stringify(response))
    
    if (response.success && response.data && response.data.list) {
      // 直接使用API返回的数据结构，不需要转换
      sites.value = response.data.list
      console.log('场站列表数据:', sites.value)
    } else {
      console.error('获取场站列表失败:', response.message || '未知错误')
    }
  } catch (error) {
    console.error('获取场站列表异常:', error)
  }
}

// 生命周期
onMounted(async () => {
  // 获取场站列表
  await fetchStationList()
  
  // 设置默认时间但不自动加载数据，等待用户操作
  const today = new Date()
  startDate.value = today.toISOString().split('T')[0]
  endDate.value = today.toISOString().split('T')[0]
  quickTime.value = 'today'
})

// 不需要 watch 监听器，改为在筛选条件变化时直接调用函数
</script>